package cn.wolfcode.shop.service;

import cn.wolfcode.shop.domain.*;
import cn.wolfcode.shop.exception.UserException;
import cn.wolfcode.shop.util.RedisConstants;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.MessageFormat;

@Service@Transactional
public class ShopCarServiceImpl implements IShopCarService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IProductSkuService productSkuService;
    @Autowired
    private IProductService productService;

    @Override
    public ShopCar addCar(String token, BigDecimal number, Long productSkuId) {
        //通过token获取用户信息
        String userKey = MessageFormat.format(RedisConstants.USER, token);
        UserLogin userLogin = (UserLogin) redisTemplate.opsForValue().get(userKey);
        if (userLogin == null) {
            throw new UserException("用户登录信息过期");
        }
        //查询该sku是否存在购物车中
        String shopCarKey = MessageFormat.format(RedisConstants.SHOP_CAR, userLogin.getId(), productSkuId);
        ShopCar shopCar = (ShopCar) redisTemplate.opsForValue().get(shopCarKey);
        if (shopCar == null) {
            ProductSku productSku = productSkuService.get(productSkuId);
            Product product = productService.getProductById(productSku.getProductId());
            shopCar = new ShopCar();
            shopCar.setNumber(number);
            shopCar.setPrice(product.getBasePrice());
            shopCar.setProductImage(product.getImage());
            shopCar.setProductName(product.getName());
            shopCar.setProductSkuId(productSku.getId());
            StringBuilder sb = new StringBuilder(50);
            for (ProductSkuProperty psp : productSku.getProductSkuPropertyList()) {
                sb.append(psp.getSkuProperty().getName()).append(":").append(psp.getValue()).append(" ");
            }
            shopCar.setSkuPropertyString(sb.toString());
        } else {
            //累加购买数量
            shopCar.setNumber(shopCar.getNumber().add(number));
        }
        redisTemplate.opsForValue().set(shopCarKey, shopCar);
        return shopCar;
    }
}
